<?php
/**
 * Created by ZIYO.REN.
 * User: sunline
 * Date: 16-5-8
 * Time: 下午2:40
 */
if(!defined('ZIYOWORD_BASE_PATH')) {
    define('ZIYOWORD_BASE_PATH', dirname(__FILE__) . '/');
    require ZIYOWORD_BASE_PATH . 'PHPWord.php';
}


class ZiyoWord {

    private $word = null;
    private $section = null;
    private $template = array();
    private $method = array(
        'text' => 'addText',
    );

    /**
     * @param array $template
     * @param array $data
     */
    function __construct($template='', $data=''){
        $this->word = new PHPWord();
        $this->word->setDefaultFontSize(12);
        if (!empty($template)) $this->template = $template;
        if (!empty($data)) $this->data = $data;
    }

    /**
     * 创建WORD文件
     * @param array $data
     * @return $this
     */
    function create($data=''){
        $data = $data ? $data : $this->data;
        if (empty($data)){
            //todo 没有数据时生成空文件呢，还是报错
        }
        $word = $this->word;

        $sectionStyle = empty($data['section']) ? null : $data['section'];
        $this->section = $word->createSection($sectionStyle);

        $tpl = $this->getTemplate();
        foreach ($tpl['items'] as $item){
            $this->parse_items($item);
        }

        return $this;
    }

    /**
     * 设置数据
     * @param array $data
     */
    function data($data){
        $this->data = $data;
        return $this;
    }

    function template($tpl){
        if (is_array($tpl)) $this->template = $tpl;
        return $this;
    }

    function getTemplate(){
        return $this->template;
    }

    function getData(){
        return $this->data;
    }

    function setStyle($style){
        return $this;
    }

    /**
     * 设置文件属性
     * @param array $properties
     * @return $this
     */
    function properties($properties=array()){
        if (empty($properties)) return $this;
        $doc_pro = $this->word->getProperties();
        foreach ($properties as $key=>$val){
            $fun = 'set'. ucfirst(strtolower($key));
            //echo $fun . "\t";
            $doc_pro->$fun($val);
        }
        return $this;
    }

    function getProperties(){
        return $this->word->getProperties();
    }

    function parse_items($item){
        if (!is_array($item)) return false;
        if (!isset($item['xtype']))  $item['xtype'] = 'text';
        $method = $item['xtype'];
        if ($method) $this->$method($item);
    }

    /**
     * 添加文本
     * @param $item
     */
    function text($item){
        $data = $this->data;
        $section = $this->section;
        $renderer = $item['renderer'] ? $item['renderer'] : '';
        $text = $item['text'] ? $item['text'] : ($item['data'] ? $data[$item['data']] : '');
        if ($renderer && function_exists($renderer)){
            $text = $renderer($text, $item, $data);
        }
        $fontStyle = $item['fontStyle'] ? $item['fontStyle'] : '';
        $paragraphStyle = $item['paragraphStyle'] ? $item['paragraphStyle'] : '';
        //echo $text. ' ||| '.  var_export($fontStyle, true) . ' ||| '. var_export($paragraphStyle,true). ' ||| ' . var_export($item, true)."<br>\n";
        $section->addText($text, $fontStyle, $paragraphStyle);
    }

    /**
     * 插入换行符
     * @param $item
     */
    function textbreak($item){
        $lines = $item['lines'] ? $item['lines'] : 1;
        $section = $this->section;
        $section->addTextBreak($lines);
    }

    function enter($item){
        $this->textbreak($item);
    }

    /**
     * 插入分页符
     * @param $item
     */
    function pagebreak($item){
        $section = $this->section;
        $section->addPageBreak();
    }

    function lists($item){
        /*$item = array(
            'xtype' => 'list',
            'listType' => PHPWord_Style_ListItem::TYPE_NUMBER,
            'items' => array(
                array(
                    'data' => '要显示的内容1',
                    'renderer' => '渲染函数',
                    'styleText' => '', //文本样式,
                    'styleList' => '', //列表样式,
                    'styleParagraph' => '', //段落样式
                ),
                array(
                    'data' => '要显示的内容2',
                    'renderer' => '渲染函数',
                    'styleText' => '', //文本样式,
                    'styleList' => '', //列表样式,
                    'styleParagraph' => '', //段落样式
                ),
            ),
        );*/
        $section = $this->section;
        foreach ( $item['items'] as $index => $list){
            $text = $list['text'] ? $list['text'] : '';
            $listStyle = array('listType'=>$item['listType']);
            $section->addListItem($text,0,null,$listStyle);
        }
    }

    function link($item){
        $section = $this->section;
        $section->addLink();
    }

    function image($item){

    }

    function memoryimage($item){

    }

    function watermark($item){

    }

    function table($item){
        $section = $this->section;
        $table = $section->addTable();
        $header = $item['header_style'];
        //$row_height = $header['height'] ? $header['height'] : 0;
        $table->addRow($header['height']);
        foreach ($item['cm'] as $index => $h_row){
            $w = $h_row['width'];
            $txt = $h_row['header'];
            $header['valign'] = $h_row['align'];
            $table->addCell($w, $header)->addText($txt);
        }
        $layer = explode('.', $item['data']);;
        $data = $this->data;
        foreach ($layer as $l){
            $data = $data[$l];
        }
        //var_export($data);
        $cell_style = $item['cell_style'][0];
        foreach ($data as $row_index => $row){
            /*var_export($row);
            echo "\n\n";*/
            $table->addRow($cell_style['height']);
            foreach ($item['cm'] as $c_index => $cell){
                $cell_style['valign'] = $cell['align'];
                $wd = $cell['width'];
                $txt = $row[ $cell['dataIndex'] ];
                $renderer = $cell['renderer'] ? $cell['renderer'] : '';
                if ($renderer && function_exists($renderer)){
                    $txt = $renderer($txt, array($row_index, $row), array($c_index, $cell), $data);
                }
                //echo $txt . "\t";
                $table->addCell($wd, $cell_style)->addText($txt);
            }
        }
    }

    function save($filename=''){
        $word = $this->word;
        $objWriter = PHPWord_IOFactory::createWriter($word, 'Word2007');
        $filename = rtrim($filename, '.docx');
        $objWriter->save($filename. '.docx');
        return true;
    }


    function __call($method, $args){
        $section = $this->section;
        $section->addText('调用的方法是：'.$method);
        //$section->addTextBreak();
        /*$section->addText('xtype是：'.$args[0]['xtype']);
        $section->addTextBreak();*/
    }

}